package com.bruce.tool.netty.socket.core;

import com.bruce.tool.common.util.IPUtils;
import com.bruce.tool.common.util.LogUtils;
import com.bruce.tool.common.util.string.JsonUtils;
import com.bruce.tool.common.util.string.MapHandler;
import com.bruce.tool.common.util.trace.TraceNoUtils;
import com.bruce.tool.netty.socket.config.ClientConfig;
import com.bruce.tool.netty.socket.constant.ClientTypeEnum;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 功能 :
 *
 * @author : Bruce(刘正航) 10:38 2019-03-10
 */
@Slf4j
@Component
public class SocketClient implements Start{

    @Autowired
    private ClientConfig config;

    @Getter
    private ClientInfo clientInfo;

    private Channel channel;
    private final Bootstrap bs = new Bootstrap();
    private final SocketClientHandler handler = new SocketClientHandler(this);

    @Getter
    private MessageListener listener;

    public void addListener(MessageListener listener){
        this.listener = listener;
    }

    @Override
    public void run() {
        clientInfo = ClientInfo.builder()
                .clientId(TraceNoUtils.fetchTraceNo())
                .clientIp(IPUtils.local())
                .clientType(config.getType())
                .build();
        EventLoopGroup group = new NioEventLoopGroup();
        bs.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress(config.getHost(), config.getPort())
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(new IdleStateHandler(config.getTimeout(), 0, 0));
                        ch.pipeline().addLast(handler);
                    }
                });
        connect();
    }

    void connect() {
        ChannelFuture channelFuture = bs.connect().addListener((ChannelFutureListener) future -> {
            if(future.isSuccess()){
                // 链接成功,立即发送心跳数据
                Map<String,Object> body = MapHandler.build().add(config.getPing(),System.currentTimeMillis());
                String ping = JsonUtils.objToStr(body);
                Message clientMessage = Message.builder()
                        .from(clientInfo)
                        .to(ClientInfo.builder()
                                .clientType(ClientTypeEnum.SERVICE.getCode())
                                .clientIp(config.getHost())
                                .port(config.getPort()).build())
                        .body(ping)
                        .build();
                String message =  JsonUtils.objToStr(clientMessage);
                future.channel().writeAndFlush(Unpooled.copiedBuffer(message.getBytes()));
                return;
            }
            LogUtils.error(log,"连接失败:{}",future.cause().getMessage());
            future.channel().eventLoop().schedule(this::connect, 10, TimeUnit.SECONDS);
        });
        channel = channelFuture.channel();
    }

    public void send(String message){
        if(StringUtils.isBlank(message)){ return; }
        if(Objects.nonNull(channel)){
            Message clientMessage = Message.builder()
                    .from(clientInfo)
                    .body(message)
                    .build();
            String messageInfo =  JsonUtils.objToStr(clientMessage);
            channel.writeAndFlush(Unpooled.copiedBuffer(messageInfo.getBytes()));
        }
    }

    public ClientConfig config(){
        return config;
    }
}
